var chatRemote = require('../remote/chatRemote');
var MongoClient = require("../../../command/MongoClient");

module.exports = function(app) {
	return new Handler(app);
};

var Handler = function(app) {
	this.app = app;
};

var handler = Handler.prototype;

/**
 * Send messages to users
 *
 * @param {Object} msg message from client
 * @param {Object} session
 * @param  {Function} next next stemp callback
 *
 */
handler.send = function(msg, session, next) {
	var channelName = session.get('channelName');
	var uid = session.uid;
	var channelService = this.app.get('channelService');
	var param = {
		msg: msg.content,
		from: uid,
		target: msg.target
	};
	channel = channelService.getChannel(channelName, false);

	//the target is all users
	if(msg.target == '*') {
		channel.pushMessage('onChat', param);
	}
	//the target is specific user
	else {
		var tuid = msg.target;
		var tsid = channel.getMember(tuid)['sid'];
		channelService.pushMessageByUids('onChat', param, [{
			uid: tuid,
			sid: tsid
		}]);
	}
	next(null, {
		route: msg.route,
		uid: uid
	});
};

handler.record = function(msg, session, next) {
	var cond = {uid: msg.uid};
	MongoClient.init();
	MongoClient.find(cond, function(data){
		if(data.length > 0){
			var level = data[0].level;
			var score = data[0].score;
			if((msg.level > level) || ((msg.level == level) && (msg.score > score))){
				var newdata = {
					uid: msg.uid,
					level: msg.level,
					score: msg.score,
					lastPlayTime: Date.now()
				};
				MongoClient.update(cond, newdata, function(data){
					if(data){
						next(null, {
							route: msg.route,
							uid: msg.uid,
							flag: true,
							message: "update success"
						});
					}else{
						next(null, {
							route: msg.route,
							uid: msg.uid,
							flag: false,
							message: "update false"
						});
					}
				});

			}else{
				next(null, {
					route: msg.route,
					uid: msg.uid,
					flag: true,
					message: "no need to update"
				});
			}
		}else{
			next(null, {
				route: msg.route,
				uid: msg.uid,
				flag: false,
				message: "no user found"
			});
		}
	});
}